package cn.edu.cdtu.healthclient.activity;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import cn.edu.cdtu.healthclient.domain.Choose;
import cn.edu.cdtu.healthclient.domain.QuestionSet;
import cn.edu.cdtu.healthclient.domain.Test;
import cn.edu.cdtu.healthclient.service.HealthService;
import cn.edu.cdtu.healthclient.service.HealthService.HealthBinder;
import cn.edu.cdtu.healthclient.task.ActivityTaskQueue;
import cn.edu.cdtu.healthclient.utils.ConnectUtil.HealthServerContect;
import cn.edu.cdtu.healthclient.utils.ConnectUtil.HealthTestPargrams;
import cn.edu.scu.healthclient.activity.R;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class QuestionActivity extends Activity {

	/*
	 * Activity任务队列。利用线程管理Activity。 
	 */
	private ActivityTaskQueue taskQueue;
	public ActivityTaskQueue getTaskQueue(){
		return taskQueue;
	}
	/*
	 * binder联系Activity与和其绑定的Service。负责他们之间的通信。
	 */
	private HealthBinder binder;
	public HealthBinder getBinder(){
		return binder;
	}
	/*
	 * 登录模块和Service服务之间的连接设置。
	 */
	private ServiceConnection serviceConnection = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			binder = null;
			taskQueue.shutdownTaskQueue();
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			binder = (HealthBinder)service;
			if(!taskQueue.isRunning()){
				taskQueue.start();
			}
		}
	};
	
	/*
	 * 实例化一个Intent对象，该对象负责启动Service后台服务。
	 */
	private final Intent serviceIntent = new Intent(HealthService.ACTION);
	
	private ListView listView;
	private TextView topTitle;
	private Test selectTest;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		startService(serviceIntent);
    	taskQueue = new ActivityTaskQueue();

		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_question);
		listView = (ListView) findViewById(R.id.health_question_list);
		topTitle = (TextView) findViewById(R.id.topTitle); 
		Intent intent = getIntent();
		selectTest = (Test) intent.getSerializableExtra(
				HealthTestPargrams.Pargram.SELECT_TEST);
		topTitle.setText(selectTest.getTest());
	}

	/* (non-Javadoc)
	 * <p>Title: onStart</p> 
	 * <p>Description: </p>  
	 * @see android.app.Activity#onStart()
	 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		bindService(serviceIntent, 
        		serviceConnection, Service.BIND_AUTO_CREATE);
		super.onStart();
		taskQueue.addTask(new Thread(new QuestionTaskImplementation()));
	}

	/* (non-Javadoc)
	 * <p>Title: onStop</p> 
	 * <p>Description: </p>  
	 * @see android.app.Activity#onStop()
	 */
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		unbindService(serviceConnection);
	}
	/**
	 * 
	 * @ClassName: QuestionTaskImplementation 
	 * @Description: TODO
	 * @author 
	 * @date 
	 *
	 */
	private class QuestionTaskImplementation implements Runnable{

		/* (non-Javadoc)
		 * <p>Title: run</p> 
		 * <p>Description: </p>  
		 * @see java.lang.Runnable#run()
		 */
		@Override
		public void run() {
			// TODO Auto-generated method stub
			Gson gson = new Gson();
			HttpClient httpClient = binder.getHttpClient();
			HttpPost httpPost = new HttpPost(HealthServerContect.SERVER_URL
					+ HealthServerContect.QUESTION_SERVLET);
			List<NameValuePair> postParams = new ArrayList<NameValuePair>();
			postParams.add(new BasicNameValuePair(
					HealthTestPargrams.Option.HEALTH_TEST_OPTION,
					HealthTestPargrams.Option
					.OptionValue.HEALTH_TEST_OPTION_GET_QUESTION_SET));
			postParams.add(new BasicNameValuePair(
					HealthTestPargrams.Pargram.SELECT_TEST, 
					gson.toJson(selectTest)));
			try {
				httpPost.setEntity(new UrlEncodedFormEntity(postParams,"utf-8"));
				HttpResponse response = httpClient.execute(httpPost);
				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					String message = EntityUtils.toString(response.getEntity());
					final List<QuestionSet> questionSetList = gson.fromJson(
							message, new TypeToken<List<QuestionSet>>(){}.getType());
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							listView.setAdapter(new QuestionApadter(questionSetList));
						}
					});
				}
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}
	/**
	 * 
	 * @ClassName: QuestionApadter 
	 * @Description: TODO
	 * @author 
	 * @date 
	 *
	 */
	private class QuestionApadter extends BaseAdapter{
		
		private QuestionSet[] questionSets;
		private List<Choose> answerList;
		private RadioGroup[] radioGroupList;
		private Button submit;
		/** 
		 * @Title: QuestionActivity.QuestionApadter
		 * @Description: TODO
		 * @throws 
		 *
		 */
		public QuestionApadter(List<QuestionSet> questionSetList) {
			// TODO Auto-generated constructor stub
			questionSets = questionSetList.toArray(
					new QuestionSet[questionSetList.size()]);
			radioGroupList = new RadioGroup[questionSetList.size()];
			submit = new Button(QuestionActivity.this);
			answerList = new ArrayList<Choose>();
			submit = new Button(QuestionActivity.this);
			submit.setText("确认提交");
			submit.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					taskQueue.addTask(new Thread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							Gson gson = new Gson();
							HttpClient httpClient = binder.getHttpClient();
							HttpPost httpPost = new HttpPost(
									HealthServerContect.SERVER_URL
									+ HealthServerContect.QUESTION_SERVLET);
							List<NameValuePair> postParams = 
									new ArrayList<NameValuePair>();
							postParams.add(new BasicNameValuePair(
									HealthTestPargrams.Option.HEALTH_TEST_OPTION,
									HealthTestPargrams.Option
									.OptionValue.HEALTH_TEST_OPTION_SUBMIT_ANSWER));
							postParams.add(new BasicNameValuePair(
									HealthTestPargrams.Pargram.SELECT_TEST, 
									gson.toJson(selectTest)));
							postParams.add(new BasicNameValuePair(
									HealthTestPargrams.Pargram.QUESTION_ANSWER,
									gson.toJson(answerList)));
							try {
								httpPost.setEntity(new UrlEncodedFormEntity(
										postParams,"utf-8"));
								HttpResponse response = httpClient.execute(httpPost);
								if (response.getStatusLine().getStatusCode() 
										== HttpStatus.SC_OK) {
									final String message = 
											EntityUtils.toString(response.getEntity());
									runOnUiThread(new Runnable() {
										
										@Override
										public void run() {
											// TODO Auto-generated method stub
											String toastString = null;
											if(HealthTestPargrams.Result
													.SUBMIT_SUCCESS.equals(message)){
												toastString = "提交成功";
											}else{
												toastString = "提交失败";
											}
											Toast.makeText(getApplicationContext(),
													toastString, 
													Toast.LENGTH_SHORT).show();
										}
									});
									QuestionActivity.this.finish();
								}
							} catch (UnsupportedEncodingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (ClientProtocolException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}	
						}
					}));
				}
			});
			for(int i=0;i<questionSets.length;i++){
				radioGroupList[i] = new RadioGroup(QuestionActivity.this);
				for(Choose choose:questionSets[i].getChooses()){
					final Choose tempChoose = choose;
					RadioButton radioButton = new RadioButton(QuestionActivity.this);
					radioButton.setText(tempChoose.getDescriptions());
					radioButton.setTag(tempChoose);
					radioGroupList[i].addView(radioButton);
				}
				radioGroupList[i].setOnCheckedChangeListener(new OnCheckedChangeListener() {
					
					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						// TODO Auto-generated method stub
						RadioButton selectRadio = 
								(RadioButton) group.findViewById(checkedId);
						Choose selectChoose = (Choose)selectRadio.getTag();
						Choose existChoose = null;
						for (Choose choose:answerList) {
							if(choose.getQuestion_id() == 
									selectChoose.getQuestion_id()){
								existChoose = choose;
								break;
							}
						}
						if(existChoose != null){
							answerList.remove(existChoose);
							answerList.add(selectChoose);
						}else{
							answerList.add(selectChoose);
						}
					}
				});
			}
		}

		/* (non-Javadoc)
		 * <p>Title: getCount</p> 
		 * <p>Description: </p> 
		 * @return 
		 * @see android.widget.Adapter#getCount()
		 */
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return questionSets.length + 1;
		}

		/* (non-Javadoc)
		 * <p>Title: getItem</p> 
		 * <p>Description: </p> 
		 * @param position
		 * @return 
		 * @see android.widget.Adapter#getItem(int)
		 */
		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		/* (non-Javadoc)
		 * <p>Title: getItemId</p> 
		 * <p>Description: </p> 
		 * @param position
		 * @return 
		 * @see android.widget.Adapter#getItemId(int)
		 */
		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}
		
		private final class ViewHolder{
			TextView questionNumber;
			TextView questionDescription;
			LinearLayout buttonLayout;
		}

		/* (non-Javadoc)
		 * <p>Title: getView</p> 
		 * <p>Description: </p> 
		 * @param position
		 * @param convertView
		 * @param parent
		 * @return 
		 * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
		 */
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder viewHolder = null;
			if(convertView == null){
				viewHolder = new ViewHolder();
				convertView = (LayoutInflater.from(QuestionActivity.this)).inflate(
						R.layout.activity_question_adapter_question,
						parent,false);
				viewHolder.questionNumber = (TextView)convertView.findViewById(R.id.question_number);
				viewHolder.questionDescription = 
						(TextView)convertView.findViewById(R.id.question_descrption);
				viewHolder.buttonLayout = 
						(LinearLayout)convertView.findViewById(R.id.question_choose_layout);
				convertView.setTag(viewHolder);
			}else {
				viewHolder = (ViewHolder)convertView.getTag();
			}
			viewHolder.buttonLayout.removeAllViews();
			if(position < questionSets.length){
				viewHolder.questionNumber.setText("第"+(position+1)+"题");
				viewHolder.questionDescription.setText("    "+
						questionSets[position].getQuestion().getDescription());
				viewHolder.buttonLayout.addView(radioGroupList[position]);
			}else {
				viewHolder.questionNumber.setText(" ");
				viewHolder.questionDescription.setText(" ");
				viewHolder.buttonLayout.addView(submit);
			}
			return convertView;
		}
		
	}
	
}
